<template>
  <div class="admin-page admin-teaching-mission">
    <!-- 页面头部 -->
    <TeachingMissionPageHeader
      @new-mission="openTeachingMissionDialog(null)"
      @download-template="downloadTemplate"
      @import-click="handleImportFile"
    />
    
    <el-card class="table-card">
      <!-- 过滤器 -->
      <TeachingMissionFilters
        :filters="filters"
        :terms="terms"
        :filtered-courses="filteredCourses"
        @term-change="onTermChange"
        @course-change="onCourseChange"
        @search="searchTeachingMissions"
        @reset="resetFilters"
      />
      
      <!-- 教学任务表格 -->
      <AdminTeachingMissionTable
        :loading="loading"
        :paginated-data="teachingMissions"
        @edit="openTeachingMissionDialog"
        @setup-teachers="openTeacherSetupDialog"
        @delete="deleteTeachingMission"
      />
      
      <!-- 分页 -->
      <div class="pagination-container">
        <Pagination
          :total="totalTeachingMissions"
          :page-size="pageSize"
          :current-page="currentPage"
          @page-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 教学任务表单对话框 -->
    <TeachingMissionFormDialog
      v-model="dialogVisible"
      :teaching-mission="currentEditingMission"
      :courses="courses"
      :terms="terms"
      :teachers="teachers"
      :lc-classes="lcClasses"
      @submit="submitTeachingMissionForm"
    />
    
    <!-- 导入对话框 -->
    <TeachingMissionImportDialog
      ref="importDialogRef"
      v-model="importDialogVisible"
      :importing="importing"
      @submit="submitImport"
      @download-template="downloadTemplate"
    />
    
    <!-- 考核组成部分对话框 -->
    <ExamPartsDialog 
      v-if="examPartsDialogVisible"
      :model-value="examPartsDialogVisible"
      :teaching-mission="currentTeachingMission"
      @update:model-value="examPartsDialogVisible = $event"
      @saved="onExamPartsSaved"
    />
    
    <!-- 学生导入对话框 -->
    <StudentImportDialog
      v-if="studentImportDialogVisible"
      :model-value="studentImportDialogVisible"
      :teaching-mission="currentTeachingMission"
      @update:model-value="studentImportDialogVisible = $event"
      @imported="onStudentsImported"
    />

    <!-- 教师设置对话框 -->
    <TeacherSetupDialog
      v-model="teacherSetupDialogVisible"
      :teaching-mission="currentTeachingMission"
      :all-teachers="teachers"
      @success="onTeacherSetupSuccess"
    />
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { teachingMissionApi } from '@/api/teaching-mission'
import { courseApi } from '@/api/base-data'
import { termApi } from '@/api/base-data'
import * as userService from '@/api/user'
import { classApi } from '@/api/base-data'

// 导入组件
import TeachingMissionPageHeader from '@/components/teaching-mission/forms/TeachingMissionPageHeader.vue'
import TeachingMissionFilters from '@/components/teaching-mission/filters/TeachingMissionFilters.vue'
import AdminTeachingMissionTable from '@/components/teaching-mission/tables/AdminTeachingMissionTable.vue'
import TeachingMissionFormDialog from '@/components/teaching-mission/dialogs/TeachingMissionFormDialog.vue'
import TeachingMissionImportDialog from '@/components/teaching-mission/dialogs/TeachingMissionImportDialog.vue'
import Pagination from '@/components/common/Pagination.vue'
import ExamPartsDialog from '@/components/teaching-mission/dialogs/ExamPartsDialog.vue'
import StudentImportDialog from '@/components/teaching-mission/dialogs/StudentImportDialog.vue'
import TeacherSetupDialog from '@/components/teaching-mission/dialogs/TeacherSetupDialog.vue'

export default {
  name: 'TeachingMission',
  components: {
    TeachingMissionPageHeader,
    TeachingMissionFilters,
    AdminTeachingMissionTable,
    TeachingMissionFormDialog,
    TeachingMissionImportDialog,
    Pagination,
    ExamPartsDialog,
    StudentImportDialog,
    TeacherSetupDialog
  },
  setup() {
    // 数据加载状态
    const loading = ref(false)
    
    // 教学任务列表数据
    const teachingMissions = ref([])
    const teachingMissionBackup = ref([])
    
    // 下拉选项数据
    const courses = ref([])
    const terms = ref([])
    const teachers = ref([])
    const lcClasses = ref([])
    
    // 过滤和分页
    const filters = reactive({
      courseId: '',
      termId: '',
    })
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 对话框状态
    const dialogVisible = ref(false)
    const importDialogVisible = ref(false)
    const importing = ref(false)
    const examPartsDialogVisible = ref(false)
    const studentImportDialogVisible = ref(false)
    const teacherSetupDialogVisible = ref(false)
    
    // 对话框引用
    const importDialogRef = ref(null)
    
    // 当前编辑/操作的教学任务
    const currentEditingMission = ref(null)
    const currentTeachingMission = ref(null)
    
    // 计算过滤后的课程列表
    const filteredCourses = computed(() => {
      // 如果没有选择学期，返回空数组
      if (!filters.termId) return []
      
      return courses.value.filter(course => {
        return teachingMissions.value.some(mission => 
          mission.courseId === course.id && mission.termId == filters.termId
        )
      })
    })
    
    // 总数据量（从后台分页获取）
    const totalTeachingMissions = ref(0)
    
    // 获取教学任务列表（使用后台分页）
    const fetchTeachingMissions = async () => {
      loading.value = true
      try {
        // 构建查询参数，包括分页和过滤条件
        const params = {
          page: currentPage.value - 1, // 后台从0开始
          size: pageSize.value
        }

        // 添加搜索条件
        if (filters.termId) {
          params.termId = filters.termId
        }
        if (filters.courseId) {
          params.courseId = filters.courseId
        }

        const response = await teachingMissionApi.getMyTeachingMissions(params)
        
        if (response && response.content) {
          // 从分页响应中获取数据
          teachingMissions.value = response.content.map(mission => {
            const enhancedMission = {
              ...mission,
              teachers: mission.teachers || [],
              lcClasses: mission.lcClasses || [],
              studentCount: mission.students ? mission.students.length : (mission.studentCount || 0),
              courseCategory: mission.course?.category || mission.courseTypeName,
              courseCredits: mission.course?.credits || mission.totalHours,
              course: mission.course || { 
                id: mission.courseId, 
                name: mission.courseName,
                category: mission.courseTypeName,
                credits: mission.totalHours
              },
              term: mission.term || { 
                id: mission.termId, 
                name: mission.termName 
              }
            };
            
            
            return enhancedMission;
          });
          
          // 更新分页信息
          totalTeachingMissions.value = response.totalElements || 0;
        } else {
          teachingMissions.value = [];
          totalTeachingMissions.value = 0;
          ElMessage.warning('获取的教学任务数据格式有误');
        }
      } catch (error) {
        console.error('获取教学任务列表失败:', error)
        ElMessage.error('获取教学任务列表失败')
        teachingMissions.value = []
        totalTeachingMissions.value = 0
      } finally {
        loading.value = false
      }
    }
    
    // 获取课程列表
    const fetchCourses = async () => {
      try {
        const response = await courseApi.getAllCourses()
        courses.value = response || []
      } catch (error) {
        console.error('获取课程列表失败:', error)
        ElMessage.error('获取课程列表失败')
      }
    }
    
    // 获取学期列表
    const fetchTerms = async () => {
      try {
        const response = await termApi.getAllTerms()
        terms.value = response || []
      } catch (error) {
        console.error('获取学期列表失败:', error)
        ElMessage.error('获取学期列表失败')
      }
    }
    
    // 获取教师列表
    const fetchTeachers = async () => {
      try {
        const response = await userService.getAllUsers()
        teachers.value = response && Array.isArray(response) 
          ? response.filter(user => user.roles && user.roles.some(role => role.name === 'ROLE_TEACHER'))
          : []
      } catch (error) {
        console.error('获取教师列表失败:', error)
        ElMessage.error('获取教师列表失败')
      }
    }
    
    // 获取队次列表
    const fetchLcClasses = async () => {
      try {
        const response = await classApi.getAllClasses()
        lcClasses.value = response || []
      } catch (error) {
        console.error('获取队次列表失败:', error)
        ElMessage.error('获取队次列表失败')
      }
    }
    
    // 获取当前学期并设置为默认值
    const fetchCurrentTerm = async () => {
      try {
        const currentTerm = await termApi.getCurrentTerm()
        if (currentTerm && currentTerm.id) {
          filters.termId = currentTerm.id
        }
      } catch (error) {
        console.warn('获取当前学期失败，将不设置默认学期:', error)
      }
    }
    
    // 打开教学任务对话框
    const openTeachingMissionDialog = (teachingMission) => {
      currentEditingMission.value = teachingMission
      dialogVisible.value = true
    }

    // 打开教师设置对话框
    const openTeacherSetupDialog = (teachingMission) => {
      currentTeachingMission.value = teachingMission
      teacherSetupDialogVisible.value = true
    }

    // 教师设置成功回调
    const onTeacherSetupSuccess = async () => {
      await fetchTeachingMissions()
    }
    
    // 提交教学任务表单
    const submitTeachingMissionForm = async (formData) => {
      try {
        if (formData.id) {
          await teachingMissionApi.updateTeachingMission(formData.id, formData)
          ElMessage.success('更新教学任务成功')
        } else {
          await teachingMissionApi.createTeachingMission(formData)
          ElMessage.success('新增教学任务成功')
        }
        
        await fetchTeachingMissions()
      } catch (error) {
        console.error('保存教学任务失败:', error)
        ElMessage.error('保存教学任务失败')
      }
    }
    
    // 删除教学任务
    const deleteTeachingMission = (teachingMission) => {
      const courseName = teachingMission.course ? teachingMission.course.name : '未知课程';
      ElMessageBox.confirm(`确定要删除"${courseName}"的教学任务吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await teachingMissionApi.deleteTeachingMission(teachingMission.id)
          ElMessage.success('删除教学任务成功')
          await fetchTeachingMissions()
        } catch (error) {
          console.error('删除教学任务失败:', error)
          ElMessage.error(`删除教学任务失败: ${error.message || '未知错误'}`)
        }
      }).catch(() => {
        // 取消删除，不做任何操作
      })
    }
    
    // 考核组成保存回调
    const onExamPartsSaved = async () => {
      ElMessage.success('考核组成保存成功！');
    }
    
    // 学生导入成功后的回调
    const onStudentsImported = async () => {
      ElMessage.success('学生导入成功！');
    }
    
    // 搜索教学任务
    const searchTeachingMissions = async () => {
      // 验证学期是否已选择
      if (!filters.termId) {
        ElMessage.warning('请先选择学期')
        return
      }
      
      currentPage.value = 1
      // 重新获取数据
      await fetchTeachingMissions()
    }
    
    // 学期变化处理器
    const onTermChange = async (newTermId) => {
      // 如果尝试清空学期，则重新设置为当前学期
      if (!newTermId) {
        try {
          const currentTerm = await termApi.getCurrentTerm()
          if (currentTerm && currentTerm.id) {
            filters.termId = currentTerm.id
            ElMessage.warning('学期不能为空，已自动设置为当前学期')
          }
        } catch (error) {
          console.warn('获取当前学期失败:', error)
          ElMessage.error('学期不能为空')
        }
        return
      }
      
      filters.termId = newTermId
      filters.courseId = ''
      currentPage.value = 1
      // 重新获取数据
      await fetchTeachingMissions()
    }
    
    // 课程变化处理器
    const onCourseChange = async (newCourseId) => {
      filters.courseId = newCourseId
      currentPage.value = 1
      // 重新获取数据
      await fetchTeachingMissions()
    }
    
    // 重置过滤器
    const resetFilters = async () => {
      try {
        // 重置课程选择
        filters.courseId = ''
        
        // 重新获取当前学期作为默认值
        const currentTerm = await termApi.getCurrentTerm()
        if (currentTerm && currentTerm.id) {
          filters.termId = currentTerm.id
        }
        
        currentPage.value = 1
        // 重新获取数据
        await fetchTeachingMissions()
      } catch (error) {
        console.warn('重置过滤器时获取当前学期失败:', error)
        // 如果获取失败，保持当前的学期选择不变
        filters.courseId = ''
        currentPage.value = 1
        // 仍然尝试重新获取数据
        await fetchTeachingMissions()
      }
    }
    
    // 处理页码变化
    const handlePageChange = (val) => {
      currentPage.value = val
      fetchTeachingMissions()
    }
    
    // 处理导入按钮点击
    const handleImportFile = () => {
      importDialogVisible.value = true
    }
    
    // 下载导入模板
    const downloadTemplate = () => {
      teachingMissionApi.downloadTemplate()
    }
    
    // 提交导入
    const submitImport = async (file) => {
      importing.value = true
      
      try {
        const formData = new FormData()
        formData.append('file', file)
        
        const result = await teachingMissionApi.importTeachingMissions(formData)
        
        // 设置导入结果到对话框
        const importResult = {
          success: result.success === true,
          message: result.success ? '导入成功' : (result.message || '导入失败'),
          data: {
            successCount: result.successCount || 0,
            failureCount: result.failureCount || 0,
            errors: result.errors || []
          }
        }
        
        // 调用对话框的设置结果方法
        if (importDialogRef.value) {
          importDialogRef.value.setImportResult(importResult)
        }
        
        // 如果成功，刷新列表并关闭对话框
        if (result.success === true) {
          ElMessage.success(`导入成功！共导入 ${result.successCount} 条教学任务`)
          await fetchTeachingMissions()
          // 延迟关闭对话框，让用户看到成功信息
          setTimeout(() => {
            importDialogVisible.value = false
          }, 2000)
        }
        
      } catch (error) {
        console.error('导入教学任务失败:', error)
        
        // 处理网络错误或其他异常
        let errorMessage = '导入失败'
        let errors = []
        
        if (error.response && error.response.data) {
          if (error.response.data.message) {
            errorMessage = error.response.data.message
          }
          if (error.response.data.errors) {
            errors = error.response.data.errors
          }
        } else if (error.message) {
          errorMessage = error.message
        }
        
        // 设置错误结果到对话框
        const importResult = {
          success: false,
          message: errorMessage,
          data: {
            successCount: 0,
            failureCount: 0,
            errors: errors.length > 0 ? errors : [errorMessage]
          }
        }
        
        if (importDialogRef.value) {
          importDialogRef.value.setImportResult(importResult)
        }
        
      } finally {
        importing.value = false
      }
    }
    
    // 页面加载时获取数据
    onMounted(async () => {
      await Promise.all([
        fetchCourses(),
        fetchTerms(),
        fetchTeachers(),
        fetchLcClasses()
      ])
      
      await fetchCurrentTerm()
      await fetchTeachingMissions()
    })
    
    return {
      loading,
      teachingMissions,
      courses,
      terms,
      teachers,
      lcClasses,
      filters,
      filteredCourses,
      currentPage,
      pageSize,
      totalTeachingMissions,
      dialogVisible,
      importDialogVisible,
      importing,
      examPartsDialogVisible,
      studentImportDialogVisible,
      teacherSetupDialogVisible,
      importDialogRef,
      currentEditingMission,
      currentTeachingMission,
      openTeachingMissionDialog,
      openTeacherSetupDialog,
      onTeacherSetupSuccess,
      submitTeachingMissionForm,
      deleteTeachingMission,
      onExamPartsSaved,
      onStudentsImported,
      onTermChange,
      onCourseChange,
      searchTeachingMissions,
      resetFilters,
      handlePageChange,
      handleImportFile,
      downloadTemplate,
      submitImport
    }
  }
}
</script>

<style scoped>
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
